<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑会员等级' : '新增会员等级'"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="等级名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入等级名称"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="等级数字" prop="level">
        <el-input-number
          v-model="form.level"
          :min="1"
          :max="999"
          placeholder="请输入等级数字"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入等级描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { createMemberLevel, updateMemberLevel, getMemberLevelDetail } from '@/api/memberLevels'

interface LevelForm {
  name: string
  level: number
  description: string
}

const props = defineProps<{
  modelValue: boolean
  levelId?: string | null
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const formRef = ref<FormInstance | null>(null)
const loading = ref(false)

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.levelId)

const form = reactive<LevelForm>({
  name: '',
  level: 1,
  description: ''
})

const rules: FormRules<LevelForm> = {
  name: [
    { required: true, message: '请输入等级名称', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请输入等级数字', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '等级数字必须在1-999之间', trigger: 'blur' }
  ]
}

// 获取等级详情
const fetchLevelDetail = async (): Promise<void> => {
  if (!props.levelId) return
  
  loading.value = true
  try {
    const res = await getMemberLevelDetail({ id: props.levelId })
    if (res.code === 200 && res.data) {
      Object.assign(form, {
        name: res.data.name || '',
        level: res.data.level || 1,
        description: res.data.description || ''
      })
      } else {
        ElMessage.error(res.message || '获取等级详情失败')
      }
  } catch (error) {
    console.error('获取等级详情失败:', error)
    // 错误信息已在 request 拦截器中处理
  } finally {
    loading.value = false
  }
}

// 监听对话框打开
watch(dialogVisible, (visible: boolean): void => {
  if (visible) {
    if (isEdit.value) {
      fetchLevelDetail()
    } else {
      // 重置表单
      Object.assign(form, {
        name: '',
        level: 1,
        description: ''
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
  }
})

const handleClose = (): void => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async (): Promise<void> => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const data: any = { ...form }
        let res
        if (isEdit.value && props.levelId) {
          data.id = props.levelId
          res = await updateMemberLevel(data)
          if (res.code === 200) {
            ElMessage.success('更新成功')
            emit('success')
            handleClose()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          res = await createMemberLevel(data)
          if (res.code === 200) {
            ElMessage.success('创建成功')
            emit('success')
            handleClose()
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存等级失败:', error)
        // 错误信息已在 request 拦截器中处理
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>

